import CommonUtil from "@/utils/common-util";
import {v4 as uuidv4} from 'uuid';
import moment from "moment";

const $message = window['$message']
// vite+minio目前不兼容，使用awos进行minio存储
import * as AWOS from 'awos-js'

export enum MinioPath {
    Image = 'resourcelib/image/',
    Audio = 'resourcelib/audio/',
    Video = 'resourcelib/video/',
    Journals = 'resourcelib/journals/',
    APK = 'resourcelib/apk/',
    XLS = 'resourcelib/xls/',
    Book = 'resourcelib/books/',
    Epub = 'resourcelib/epub/',
    Config = 'resourcelib/config/',
    Netliterature = 'resourcelib/netliterature/',
    Copyright = 'resourcelib/copyright/',
}

export const bucketName = CommonUtil.getMinIoConfig().bucket;
export let xhrList: any = [];

interface UploadOption {
    mode?: 'single' | 'multiple',
    type?: Array<string>;
    size?: number;
}


export default class MinClient {

    /**
     * 通用文件选择
     * @param option {文件类型}
     */
    static selectFile(option: UploadOption) {
        const {type, mode, size} = option;
        return new Promise((resolve) => {
            const inputNode = document.createElement('input');
            inputNode.setAttribute('type', 'file');
            if (type) {
                inputNode.setAttribute('accept', type.toString());
            }
            inputNode.style.display = 'none';
            if (mode && mode === 'multiple') {
                inputNode.setAttribute('multiple', 'multiple');
            }
            document.body.appendChild(inputNode);
            inputNode.click();
            inputNode.onchange = () => {
                if (mode === 'multiple') {
                    const allFileList: any = inputNode['files'];
                    if (allFileList) {
                        for (var i = 0; i < allFileList.length; i++) {
                            let file: any = allFileList[i];
                            const fileName = file.name;
                            let reg = /(.*)$/i;
                            if (type) {
                                reg = new RegExp(`(${type.join('|')})$`, 'i');
                            }
                            if (reg.test(fileName)) {
                                file.pass = true;
                            } else {
                                if (type) {
                                    file.pass = false;
                                }
                            }
                            if (option.size && option.size * 1024 < file.size) {
                                $message.error(`文件大小超出限制, 最大支持${option.size / 1024}M,已自动过滤`)
                                file.pass = false;
                            }
                        }
                    }
                    let fileList = Array.from(allFileList);
                    resolve(fileList.filter((item: any) => item.pass));
                } else {
                    if (inputNode['files']) {
                        const file = inputNode['files'][0];
                        if (option.size && option.size * 1024 < file.size) {
                            $message.error(`文件大小超出限制, 最大支持${option.size / 1024}M,已自动过滤`)

                            return;
                        }
                        const fileName = file.name;
                        let reg = /(.*)$/i;
                        if (type) {
                            reg = new RegExp(`(${type.join('|')})$`, 'i');
                        }
                        if (reg.test(fileName)) {
                            resolve(file);
                        } else {
                            if (type) {
                                $message.error(`文件格式不正确，仅支持${type.join()}`)
                            }
                        }
                        // 将节点在body上移除
                        document.body.removeChild(inputNode);
                    }
                }
            };
        });
    }

    /**
     * 分片上传
     */
    static bigFileUpload = (uploadPath, file, callBack?, randomName?) => {
        let config: any = CommonUtil.getMinIoConfig();
        const minioClient = new AWOS.Client({
            type: 'aws',
            awsOptions: {
                accessKeyId: config.accessKey,
                secretAccessKey: config.secretKey,
                bucket: bucketName,
                // when use aws, endpoint is unnecessary and region must be set
                region: "Fus-east-1",
                endpoint: 'http://192.168.196.50:9000',
                // when use minio, S3ForcePathStyle must be set true
                s3ForcePathStyle: true,
                SSL: false
            }
        })
        const names = file.name.split('.');
        let fileName = `${uploadPath}${file.name}`;
        if (randomName) {
            // uuid生成文件名称
            fileName = `${uploadPath}${uuidv4().replace(/-/g, '')}.${names[names.length - 1]}`;
        }
        return new Promise(async (resolve, reject) => {
            // await minioClient.put(fileName,file)
            minioClient.signatureUrl(fileName,{method:'PUT',expires:86400}).then(presignedUrl => {
                let xhr = new XMLHttpRequest();
                xhr.open("PUT", presignedUrl, true);
                xhr.withCredentials = false;
                xhr.setRequestHeader(
                    "x-amz-date",
                    moment()
                        .utc()
                        .format("YYYYMMDDTHHmmss") + "Z"
                );
                xhr.upload.addEventListener("progress", event => {
                    if (event.lengthComputable) {
                        let complete = (event.loaded / event.total * 100 | 0);
                        callBack ? callBack(complete) : '';
                        if (complete === 100) {
                            resolve(presignedUrl.substring(presignedUrl.indexOf('/resourcelib'), presignedUrl.indexOf('?X-Amz-Algorithm')));
                        }
                    }
                });
                xhr.send(file);
                xhrList.push(xhr);
            })
        });
    };

    static abortAllXhr() {
        xhrList.map(item => {
            item.abort();
        });
        xhrList = [];
    }
}
